//
//  MTPartyInviteInfoViewController.swift
//  MT
//
//  Created by ooops on 2020/5/26.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import YPNavigationBarTransition

extension MTPartyInviteInfoViewController: MTInviteInfoCellDelegate, MTRequestVerifyDelegate, MTInviteUserInfoCellDelegate {
    
    func confrimInvitation(userName: String) {
        self.tableView.reloadData()
    }
    
    func rejectInvitation() {
        self.tableView.reloadData()
    }
    
    func acceptInvitation(userName: String, eventType: Int, pushId: String?) {
        let requestParam: [String : Any] = ["eventType": eventType, "pushId": pushId ?? "", "userName": userName]
        
        UserCenterApiTool.notify(provider: userProvider, requestParam: requestParam, complete: { (model) in
            
        }) { (error) in
            
        }
    }
    
    func communication(pushId: String) {
        JMSGConversation.createGroupConversation(withGroupId: pushId) { (result, error) in
            if let conv = result as? JMSGConversation {
                let vc = JCChatViewController(conversation: conv, true)
//                NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateConversation), object: nil, userInfo: nil)
//                self.navigationController?.pushViewController(vc, animated: true)
                if let baseTabBarViewController = (UIApplication.mt_keyWindow?.rootViewController as? BaseTabBarViewController) {
                    self.navigationController?.popToRootViewController(animated: false)
                    baseTabBarViewController.selectedIndex = 1
                    if let nav = baseTabBarViewController.selectedViewController as? BaseNavController {
                        DispatchQueue.main.after(0.25) {
                            nav.pushViewController(vc, animated: true)
                        }
                    }
                }
            }
        }
    }
}

extension MTPartyInviteInfoViewController: UITableViewDelegate, UITableViewDataSource {
    
    //MARK: UITableViewDataSource
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return result.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let v = result[indexPath.row]
        /// 发布者视图
        if v.roleType == 1 {
            let cell: MTInviteInfoCell = tableView.dequeueReusableCell(withIdentifier: MTInviteInfoCell.reuseIdentity(), for: indexPath) as! MTInviteInfoCell
            cell.delegate = self
            cell.model = v
            return cell
        }
        let cell: MTInviteUserInfoCell = tableView.dequeueReusableCell(withIdentifier: MTInviteUserInfoCell.reuseIdentity(), for: indexPath) as! MTInviteUserInfoCell
        cell.delegate = self
        cell.model = v
        cell.delegate = self
        return cell
    }
    
    //MARK: UITableViewDelegate
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
//    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        return UITableView.automaticDimension
//    }
//
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 11
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
}

class MTPartyInviteInfoViewController: BaseViewController {
    
    private var currentPage: Int = 1
    private let pageSize: Int = 20
    private var loadType: Int = 1
    private var clubType: Int = 0
    var partyId: Int?
    
    /// MTProvider
    fileprivate lazy var taskProvider: MTProvider<MTCreateTaskAPI> = {
        return MTProvider<MTCreateTaskAPI>(plugins: [])
    }()
    
    fileprivate let userProvider: MTProvider = MTProvider<UserCenterApi>()
    
    private var result: [MTTaskInviteInfoSubModel] = []
    
    override func refreshView() {
        loadFirst()
    }
    
    private func loadRequestData(loadMore: Bool) {
        var queryParam: [String : Any] = ["curPage" : currentPage, "pageSize" : pageSize]
        //partyId
        if let pid = partyId {
            queryParam.updateValue(pid, forKey: "partyId")
        }
        MTCreateTaskTool.queryNotify(provider: taskProvider, parameters: queryParam, complete: { [weak self] (model) in
            
            guard let weakSelf = self else { return }
            weakSelf.comporseData(model: model, loadMore: loadMore)
            
        }) {(_) in
            
        }
    }
    
    private func comporseData(model: MTTaskInviteInfoModel?, loadMore: Bool) {
        weak var weakSelf = self
        weakSelf?.tableView.mj_footer?.endRefreshing()
        weakSelf?.tableView.mj_header?.endRefreshing()
        if weakSelf?.currentPage == 1 {
            weakSelf?.tableView.mj_footer?.state = .idle
        }
        
        if let m = model {
            debugPrint("message: ", m.message ?? "")
            if let r = m.result {
                if (m.page?.pages == weakSelf?.currentPage) {
                    weakSelf?.tableView.mj_footer?.endRefreshingWithNoMoreData()
                }
                if loadMore == true {
                    weakSelf?.result = weakSelf!.result + r
                } else {
                    weakSelf?.result = r
                }
                
                weakSelf?.hiddenHF(isHidden: weakSelf?.result.count == 0)
            } else {
                weakSelf?.hiddenHF(isHidden: true)
            }
            
            DispatchQueue.main.async {
                weakSelf?.tableView.reloadData()
            }
        }
    }
    
    @objc private func hiddenHF(isHidden: Bool) {
        self.tableView.mj_header?.isHidden = isHidden
        self.tableView.mj_footer?.isHidden = isHidden
    }
    
    @objc func loadFirst() {
        self.currentPage = 1
        
        loadRequestData(loadMore: false)
    }
    
    @objc private func loadMore() {
        
        self.currentPage = self.currentPage + 1
        
        loadRequestData(loadMore: true)
        
    }
    
    lazy var tableView: UITableView = {
        let table = UITableView(frame: view.bounds, style: .grouped)
        table.delegate = self
        table.dataSource = self
        table.register(MTInviteInfoCell.self, forCellReuseIdentifier: MTInviteInfoCell.reuseIdentity())
        table.register(MTInviteUserInfoCell.self, forCellReuseIdentifier: MTInviteUserInfoCell.reuseIdentity())
        table.separatorStyle = .none
        table.tableFooterView = UIView()
        table.estimatedRowHeight = 144
        table.rowHeight = UITableView.automaticDimension
//        table.sectionHeaderHeight = 0
//        table.sectionFooterHeight = 10
        table.emptySetView = ViewFactory.emptySetView(nil, nil, { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.loadRequestData(loadMore: false)
        })
        return table
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "待处理请求"
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        loadFirst()
    }
}


extension MTPartyInviteInfoViewController {
    
    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .backgroundStyleOpaque, .showShadowImage]
    }
}
